package leetcode.jianzhioffer;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-11-07 23:58
 **/
public class JianZhiOffer68II {

    TreeNode ancestor;

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        dfs(root, p, q);
        return this.ancestor;
    }

    private boolean dfs(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return false;
        }
        boolean lson = dfs(root.left, p , q);
        boolean rson = dfs(root.right, p, q);
        if (lson && rson || ((root.val == p.val || root.val == q.val) && (lson || rson))) {
            ancestor = root;
        }
        return lson || rson || root.val == p.val || root.val == q.val;
    }
}
